package main

import (
	yamlv3 "gopkg.in/yaml.v3"
	"k8s.io/apimachinery/pkg/util/json"
	"os"
	"path/filepath"

	"k8s.io/apimachinery/pkg/runtime"
)

// ----------------------------- FILE HELPERS -----------------------------

// ensureDir确保目录存在，若不存在则创建
func ensureDir(path string) error {
	return os.MkdirAll(path, 0o755)
}

// writeYAML将YAML文档写入指定路径
func writeYAML(path string, docs [][]byte) error {
	if err := ensureDir(filepath.Dir(path)); err != nil {
		return err
	}
	f, err := os.Create(path)
	if err != nil {
		return err
	}
	defer f.Close()
	for i, d := range docs {
		if i > 0 {
			if _, err := f.WriteString("---\n"); err != nil {
				return err
			}
		}
		if _, err := f.Write(d); err != nil {
			return err
		}
		if len(d) > 0 && d[len(d)-1] != '\n' {
			if _, err := f.WriteString("\n"); err != nil {
				return err
			}
		}
	}
	return nil
}

// objToMap将Kubernetes对象转换为map[string]any
func objToMap(obj runtime.Object) (map[string]any, error) {
	j, err := json.Marshal(obj)
	if err != nil {
		return nil, err
	}
	m := map[string]any{}
	if err := json.Unmarshal(j, &m); err != nil {
		return nil, err
	}
	return m, nil
}

// mapToYAML将map转换为YAML格式的字节切片
func mapToYAML(m map[string]any) ([]byte, error) {
	return yamlv3.Marshal(m)
}
